﻿using Quartz;
/*
需要引用的包 
Quartz
Quartz.Extensions.Hosting 
*/

namespace WeWork.Service.Core.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class QuartzExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="quartz"></param>
        /// <param name="config"></param>
        /// <exception cref="Exception"></exception>
        public static void AddJobAndTrigger<T>(this IServiceCollectionQuartzConfigurator quartz, IConfiguration config) where T : IJob
        {
            // Use the name of the IJob as the appsettings.json key
            string jobName = typeof(T).Name;

            // Try and load the schedule from configuration
            var configKey = $"Quartz:{jobName}";
            var cronSchedule = config[configKey];

            // Some minor validation
            if (string.IsNullOrEmpty(cronSchedule))
            {
                throw new Exception($"No Quartz.NET Cron schedule found for job in configuration at {configKey}");
            }

            // register the job as before
            var jobKey = new JobKey(jobName);
            quartz.AddJob<T>(opts => opts.WithIdentity(jobKey));

            quartz.AddTrigger(opts => opts
                .ForJob(jobKey)
                .WithIdentity(jobName + "-trigger")
                .WithCronSchedule(cronSchedule)); // use the schedule from configuration
        }
        public static IServiceCollectionQuartzConfigurator ExecuteByCron<T>(this IServiceCollectionQuartzConfigurator configurator, string cronExpression) where T : IJob
        {
            var jobName = typeof(T).Name;
            var jobKey = new JobKey(jobName);

            configurator.AddJob<T>(opts => opts.WithIdentity(jobKey));

            configurator.AddTrigger(opts => opts
                .ForJob(jobKey)
                .WithIdentity($"{jobName}-trigger")
                .WithCronSchedule(cronExpression));

            return configurator;
        }
    }
}
